import React, { Component } from 'react';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import { Card, message, Button, Form, Input, Radio, Upload, Icon, Select, InputNumber } from 'antd';
import { uploadUrl } from '@/config/index';
import { connect } from 'dva';
import { router } from 'umi';
import { getParam } from '@/utils/utils.js';
import {isEqual} from "lodash";
import RouterWillLeave from "@/components/RouterWillLeave";
import MotionService from './services';

const { TextArea } = Input;
const { Option } = Select;
function getToken() {
  const token = localStorage.getItem('token');
  return token;
}
@Form.create()
@connect(({ order }) => ({ ...order }))
export default class RollUpDetails extends Component {
  state = {
    fileList: [],
    fileListVice: [],
    data: {},
    originValues: {},
    isSubmit: false
  };

  componentDidMount() {
    const values = this.props.form.getFieldsValue()
    this.setState({
      originValues: values,
    });
    if (getParam('id')) {
      MotionService.productExchangeQueryDetail({ id: getParam('id') }).then(res => {
        this.setState({
          data: res,
          originValues: values,
          fileList: res.subPicList,
          fileListVice: res.mainPicObj,
        }, () => {
          const values = this.props.form.getFieldsValue()
          this.setState({
            originValues: values,
          });
        });
      });
    }
    this.props.dispatch({
      type: 'order/PlateformChannel',
    });
  }

  handleSubmit = e => {
    e.preventDefault();
    this.props.form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        this.setState({
          isSubmit: true
        });
        const { fileList, fileListVice } = this.state;
        const newFileList = fileList.map(item => {
          if (item.response) {
            return item.response.data;
          }
            return item.url;
          
        });
        const newFileListVice = fileListVice.map(item => {
          if (item.response) {
            return item.response.data;
          }
            return item.url;
          
        });
        if (getParam('id')) {
          MotionService.productExchangeUpdate({
            ...values,
            mainPic: newFileListVice[0],
            subPicUrls: newFileList,
            id: getParam('id'),
          }).then(res => {
            message.success('修改成功！');
            router.push('/Motion/RollUp');
          });
        } else {
          MotionService.productExchangeAdd({
            ...values,
            mainPic: fileListVice[0].response.data,
            subPicUrls: newFileList,
          }).then(res => {
            message.success('新增成功！');
            router.push('/Motion/RollUp');
          });
        }
      }
    });
  };

  onRemove = file => {
    this.setState({
      fileList: this.state.fileList.filter(item => item.url !== file.url),
    });
    return true;
  };

  onRemoveVice = file => {
    this.setState({
      fileListVice: this.state.fileListVice.filter(item => item.url !== file.url),
    });
    return true;
  };

  handleChange = ({ file, fileList, event }) => {
    this.setState({
      fileList,
    });
  };

  handleChangeVice = ({ file, fileList, event }) => {
    this.setState({
      fileListVice: fileList,
    });
  };
  
  renderRouterWillLeave=()=>{
    const values = this.props.form.getFieldsValue()
  
    const { originValues, isSubmit } = this.state
    const isPrompt = !isEqual(values, originValues)
    return (
      <RouterWillLeave isPrompt={isPrompt} isSubmit={isSubmit}  />
    )
  }
  
  render() {
    const { fileList, fileListVice, data } = this.state;

    const { PlateformList } = this.props;
    const formItemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 6 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 12 },
      },
    };
    const uploadButton = (
      <div>
        <Icon type="plus" />
        <div className="ant-upload-text">Upload</div>
      </div>
    );
    const { getFieldDecorator } = this.props.form;
    return (
      <PageHeaderWrapper>
        {
          this.renderRouterWillLeave()
        }
        <Card bordered={false}>
          <Form {...formItemLayout} onSubmit={this.handleSubmit}>
            <Form.Item label="商品名称">
              {getFieldDecorator('productName', {
                rules: [
                  {
                    required: true,
                    message: '请输入商品名称!',
                  },
                ],
                initialValue: data && data.productName,
              })(<Input placeholder="请输入" disabled={getParam('status')} />)}
            </Form.Item>
            <Form.Item label="库存数量">
              {getFieldDecorator('totalStock', {
                rules: [
                  {
                    required: true,
                    message: '请输入库存数量!',
                  },
                ],
                initialValue: data && data.totalStock,
              })(
                <InputNumber
                  placeholder="请输入数量"
                  style={{ width: 129 }}
                  disabled={getParam('status')}
                />,
              )}
            </Form.Item>
            <Form.Item label="上架渠道">
              {getFieldDecorator('channelId', {
                rules: [
                  {
                    required: true,
                    message: '请选择！',
                  },
                ],
                initialValue: data && data.channelId,
              })(
                <Select placeholder="请选择" style={{ width: 180 }} disabled={getParam('status')}>
                  {PlateformList.map((item, val) => {
                    return (
                      <Option value={item.channelId} key={val}>
                        {item.channelName}
                      </Option>
                    );
                  })}
                </Select>,
              )}
            </Form.Item>
            <Form.Item label="销售原价">
              {getFieldDecorator('salePrice', {
                rules: [
                  {
                    required: true,
                    message: '请输入销售原价!',
                  },
                ],
                initialValue: data && data.salePrice,
              })(
                <Input
                  placeholder="请输入价格"
                  style={{ width: 129 }}
                  disabled={getParam('status')}
                />,
              )}
            </Form.Item>
            <Form.Item label="兑换点券">
              {getFieldDecorator('exchangePoint', {
                rules: [
                  {
                    required: true,
                    message: '请输入兑换点券!',
                  },
                ],
                initialValue: data && data.exchangePoint,
              })(
                <InputNumber
                  placeholder="请输入"
                  style={{ width: 224 }}
                  disabled={getParam('status')}
                />,
              )}
            </Form.Item>
            <Form.Item label="商品主图">
              {getFieldDecorator('mainPic', {
                rules: [
                  {
                    required: true,
                    message: '请上传图片，图片不能为空',
                  },
                ],
                initialValue: fileListVice,
              })(
                <div className="upload-desc">
                  <Upload
                    accept="image/*"
                    action={uploadUrl}
                    headers={{
                      token: getToken(),
                    }}
                    disabled={getParam('status')}
                    listType="picture-card"
                    fileList={fileListVice}
                    // onPreview={this.handlePreview} //预览
                    onRemove={this.onRemoveVice} // 删除
                    onChange={this.handleChangeVice}
                  >
                    {fileListVice.length >= 1 ? null : uploadButton}
                  </Upload>
                  <div className="size-desc">
                    <span>建议尺寸： 336px*280px</span>
                  </div>
                </div>,
              )}
            </Form.Item>
            <Form.Item label="商品副图">
              {getFieldDecorator('subPicUrls', {
                rules: [
                  {
                    required: true,
                    message: '请上传图片，图片不能为空',
                  },
                ],
                initialValue: fileList,
              })(
                <div className="upload-desc">
                  <Upload
                    accept="image/*"
                    action={uploadUrl}
                    headers={{
                      token: getToken(),
                    }}
                    disabled={getParam('status')}
                    listType="picture-card"
                    fileList={fileList}
                    // onPreview={this.handlePreview} //预览
                    onRemove={this.onRemove} // 删除
                    onChange={this.handleChange}
                  >
                    {fileList.length >= 8 ? null : uploadButton}
                  </Upload>
                  <div className="size-desc">
                    <span>建议尺寸：612px*416px</span>
                  </div>
                </div>,
              )}
            </Form.Item>
            <Form.Item label="兑换规则">
              {getFieldDecorator('exchangeRule', {
                rules: [
                  {
                    required: true,
                    message: '请输入兑换规则!',
                  },
                ],
                initialValue: data && data.exchangeRule,
              })(
                <TextArea
                  placeholder="请输入"
                  rows={4}
                  style={{ width: 313 }}
                  disabled={getParam('status')}
                />,
              )}
            </Form.Item>
            <Form.Item label="是否上架">
              {getFieldDecorator('status', {
                rules: [
                  {
                    required: true,
                    message: '请选择!',
                  },
                ],
                initialValue: data && data.status,
              })(
                <Radio.Group disabled={getParam('id') || getParam('status')}>
                  <Radio value="PUT_ON_SHELF">立即上架</Radio>
                  <Radio value="PUT_ON_DEPOT">放入仓库</Radio>
                </Radio.Group>,
              )}
            </Form.Item>
            <Form.Item style={{ textAlign: 'center' }}>
              {getParam('status') ? (
                <Button type="primary" onClick={() => router.push('/Motion/RollUp')}>
                  返回
                </Button>
              ) : (
                <Button type="primary" htmlType="submit">
                  提交
                </Button>
              )}
            </Form.Item>
          </Form>
        </Card>
      </PageHeaderWrapper>
    );
  }
}
